package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;


//无效网址
public class DzhtvNewsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		boolean bRet=false;

		String[] regex={
				"http://www.dzhtv.com/.*/[0-9]*/[0-9]*/[0-9]*.html",
				"http://www.dzhtv.com/html/[0-9]{4}/[a-z]*_[0-9]{4}/[0-9]+.html"
							};
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				bRet=true;
				break;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		String html=urlMeta.getHtml();
		String title= null;
		String content= null;
		String author = null;
		Long date = null;
		int commentNum=0;
		int clickNum=0;
		NewsMeta meta=new NewsMeta();
		meta.setUrl(url);
		meta.setType(0);
		Document doc=Jsoup.parse(html);
		urlMeta=null;
		/*
		 * 解析新闻标题
		 */
		title=doc.select("h1").html();
		if(StringUtils.isBlank(title)) {
			title=doc.select("span.bread-cur").html();
		}
		/*
		 * 解析时间
		 */
		date=DateUtils.matchDate(doc.select(".info").text());
		if(date==null){
			date=DateUtils.matchDate(doc.select("h1 span").text());
		}
		
		content=HtmlCleaner.getContentHtml(url,doc.select("div.content").first());
		if(title.contains("<br />")){
			title=title.substring(0, title.indexOf("<br />"));
		}
		author=JSoupUtils.matchAuthor(doc,"来源：");
		meta.setAuthor(author);
		//clickNum=NumberUtils.matchNumber(doc.select("#hits").text());

		meta.setTitle(title);
		meta.setContent(content);
		meta.setDate(date);
		meta.setClickNum(clickNum);
		meta.setCommentNum(commentNum);

		return meta;
	}


	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	public static void main(String[] args) {
		String url="http://www.dzhtv.com/yule/2015/0305/1312.html";
		DzhtvNewsAnalyse a=new DzhtvNewsAnalyse();
		UrlMeta urlMeta=CrawlHTML.responseToURL(url);
		url = UrlArgumentTop.FromatUrl(url);
		System.out.println(UrlArgumentTop.FromatUrl(url));
		System.out.println(a.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(a.parserHtml(meta));
		

	}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
